package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * 订单定时任务
 * 定时处理订单状态：超过15分钟未支付自动取消订单 凌晨一点自动完成派送
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private  OrderMapper orderMapper;

    public OrderTask(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")  // 每分钟执行一次  这个注解表示  任务触发时间
    public void processTimeoutOrders(){
        log.info("定时处理订单是否 支付 状态");
        //将现在时间减去15分钟  时间为十五分钟之前  在这之前的未支付订单自动取消
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //查询15分钟之前的 并 未下单的订单
        List<Orders> byStatusAndOrderTime = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT, time);
        //判断是否存在
        if (byStatusAndOrderTime != null && byStatusAndOrderTime.size() > 0){
            //遍历取消订单
            for (Orders orders : byStatusAndOrderTime) {
                orders.setCancelReason("订单支付超时，取消订单");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.cancel(orders);
            }
        }
    }

    /**
     * 处理处于派送状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?") // 每天凌晨一点执行一次
    public void processDeliveryOrder(){
        log.info("定时处理处于派送状态的订单开始");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);//提前60分钟 处理的是昨天的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList != null && ordersList.size() > 0){
            for (Orders orders : ordersList) {
                orders.setDeliveryTime(LocalDateTime.now());
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
